local _M = {}

local uuid = require "resty.jit-uuid"
local statusEnum = require "consts.scanStatus"
-- local uuidCache = ngx.shared.randomCodeCache
local cjson = require "cjson"

local expiredTime = 10 * 60 -- 缓存过期时间，单位ms

-- init

-- 创建随机码
function _M.createRandomNum()
    -- 创建一个随机码，并放进缓存
    local randomNum = uuid()
    local redisConn = getRedisConn();
    local res, err = redisConn:set(randomNum, statusEnum.NOT_SCANED)
    redisConn:expire(randomNum, expiredTime)
    if err then 
        ngx.log(ngx.ERR, err)
    end
    -- uuidCache:set(randomNum, statusEnum.NOT_SCANED, expiredTime)
    closeRedisConn(redisConn)
    ngx.print(cjson.encode({randomNum = randomNum}))
end


-- 查询随机码扫码状态
function _M.getRandomNumScanStatus(randomNum) 
    if randomNum ~= nil and randomNum ~= '' then
        local redisConn = getRedisConn();
        local val = redisConn:get(randomNum)
        ngx.print(val)
        closeRedisConn(redisConn)
    else
        ngx.print("param is empty")
    end
end


-- 把随机码扫码状态置为已扫码
function _M.scanRandomNum(randomNum) 
    if randomNum ~= nil and randomNum ~= '' and uuidCache:get(randomNum) ~= nil then
        local redisConn = getRedisConn();
        redisConn:set(randomNum, statusEnum.SCANED)
        redisConn:expire(randomNum, redisConn:ttl(randomNum))
        ngx.print("success")
    else 
        ngx.print("randomNum not exists")
    end
end


function getRedisConn() 
    local redis = require "resty.redis"
    local redisConn = redis:new()
    redisConn:set_timeouts(1000, 1000, 1000) -- 设置创建连接，发送数据和接收数据的超时时间，单位ms
    local ok, err = redisConn:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("redis connect failed")
        return
    end
    return redisConn
end

function closeRedisConn(redis_conn) 
    if not redis_conn then
        return
    end

    local pool_max_idle_time = 10000
    local pool_size = 2000
    local ok, err = redis_conn:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "set keepalive error")
    end
end

return _M